package com.aizhixin.lab.course.template.controller;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.core.PageData;
import com.aizhixin.lab.common.core.UserInforCore;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.company.entity.Professional;
import com.aizhixin.lab.company.service.ProfessionalService;
import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.course.template.domain.ImportResultDomain;
import com.aizhixin.lab.course.template.domain.TemplateDomain;
import com.aizhixin.lab.course.template.dto.TemplateDTO;
import com.aizhixin.lab.course.template.entity.Template;
import com.aizhixin.lab.course.template.repository.TemplateRepository;
import com.aizhixin.lab.course.template.service.TemplateImportService;
import com.aizhixin.lab.course.template.service.TemplateService;
import com.aizhixin.lab.task.domain.StuTaskDetailsDomain;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/course/template")
@Api(value = "课程模板相关API")
public class TemplateController {
    @Autowired
    private TemplateRepository templateRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private TemplateService templateService;
    @Autowired
    private TemplateImportService importService;
    @Autowired
    private Config config;
    @Autowired
    private ProfessionalService professionalService;
    @RequestMapping(value = "/getList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "查询课程列表", response = Void.class, notes = "查询课程列表<br>@author hsh")
    public ResponseEntity<?> getList(@RequestHeader("Authorization") String token,
                                     @ApiParam(value = "name", required = false) @RequestParam(value = "name", required = false) String name,
                                     @ApiParam(value = "type 0:全部 10:理论课 20:实验课", required = false) @RequestParam(value = "type", required = false) Integer type,
                                     @ApiParam(value = "isPublish 0:全部 10:未发布 20:已发布", required = false) @RequestParam(value = "isPublish", required = false) Integer isPublish,
                                     @ApiParam(value = "专业ID") @RequestParam(value = "profId", required = false) Long profId,
                                     @ApiParam(value = "deleteFlag 0:未删除 1已删除", required = false) @RequestParam(value = "deleteFlag", required = false) Integer deleteFlag,
                                     @ApiParam(value = "pageNumber 起始页") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
                                     @ApiParam(value = "pageSize 每页的限制数目") @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        PageData<Template> result;
        if (UserInforCore.ROLE_TEACHER.equals(account.getRole())){
             result = templateService.getList(name, type, isPublish,profId, pageNumber, pageSize,account.getId(),deleteFlag);
        }else {
            result = templateService.getList(name, type, isPublish,profId, pageNumber, pageSize,null,deleteFlag);
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/getAllProfessional", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "获取登录人所属学院下所有专业列表", response = Void.class, notes = "获取登录人所属学院下所有专业列表<br>@author lwq")
    public ResponseEntity<?> getAllProfessional(@RequestHeader("Authorization") String token) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        List<Professional> allProfessional = professionalService.getAllProfessional(account.getCollegeId());
        return new ResponseEntity(allProfessional, HttpStatus.OK);
    }
    @RequestMapping(value = "/nameIsExits", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "判断课程名称是否存在", response = Void.class, notes = "判断课程名称是否存在<br>@author lwq")
    public ResponseEntity<?> nameIsExits(@RequestHeader("Authorization") String token,
                                         @ApiParam(value = "name", required = false) @RequestParam(value = "name", required = false) String name) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Boolean exist = templateService.isExist(name);
        return new ResponseEntity(exist, HttpStatus.OK);
    }

    @RequestMapping(value = "/getTemplate", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "查询课程", response = Void.class, notes = "查询课程<br>@author hsh")
    public ResponseEntity<?> getTemplate(@RequestHeader("Authorization") String token,
                                         @ApiParam(value = "templateId", required = false) @RequestParam(value = "templateId", required = false) Long templateId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        TemplateDomain result = templateService.getTemplate(templateId);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/publish", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "发布课程模板", response = Void.class, notes = "发布课程模板<br>@author hsh")
    public ResponseEntity<?> save(@RequestHeader("Authorization") String token,
                                  @ApiParam(value = "templateId", required = false) @RequestParam(value = "templateId", required = false) Long templateId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = templateService.publish(templateId);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "添加课程模板", response = Void.class, notes = "添加课程模板<br>@author hsh")
    public ResponseEntity<?> save(@RequestHeader("Authorization") String token,
                                  @ApiParam(value = "type 10:理论课 20:实验课", required = false) @RequestBody TemplateDTO dto) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result =new HashMap<>();
       if (dto.getId()==null&&templateService.isExist(dto.getName())){
           result.put(ApiReturnConstants.SUCCESS,false);
           result.put(ApiReturnConstants.MESSAGE,"课程名已存在");
           return new ResponseEntity(result, HttpStatus.OK);
       }

        result = templateService.save(dto,account);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "DELETE", value = "删除课程模板", response = Void.class, notes = "删除课程模板<br>@author hsh")
    public ResponseEntity<?> delete(@RequestHeader("Authorization") String token,
                                    @ApiParam(value = "templateId", required = true) @RequestParam(value = "templateId") Long templateId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        Map<String, Object> result = templateService.delete(templateId);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "POST", value = "导入课程模板", response = Void.class, notes = "导入课程模板<br>@author hsh")
    public ResponseEntity<?> importData(@RequestHeader("Authorization") String token,
                                        @ApiParam(value = "templateId", required = true) @RequestParam(value = "templateId") Long templateId,
                                        @ApiParam(value = "Excel数据文件", required = true) @RequestParam(value = "file") MultipartFile file) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
//        AccountDTO account = new AccountDTO();
//        account.setId(1l);
        ImportResultDomain result = importService.importResult(account.getId(), templateId);
        if (result == null || result.getState().intValue() != 10) {
            try {
                File dest = new File(config.getBaseDir() + "/" + file.getOriginalFilename());
                FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
                importService.importData(account.getId(), templateId, file.getOriginalFilename(), dest);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/daochu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "导出", response = Void.class, notes = "导出<br>@author hsh")
    public void ex() throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
        List<Template> templateList = templateRepository.findByDeleteFlag(DataValidity.VALID.getState());

        HSSFSheet sheet = wb.createSheet("课程表");
        HSSFRow row = sheet.createRow(0);
        row.createCell(1).setCellValue("课程名字");
        row.createCell(2).setCellValue("课时量");
        row.createCell(3).setCellValue("类型（理论，还是实践）");
        row.createCell(0).setCellValue("序号");
        int i = 1;
        for (Template template:templateList) {
            HSSFRow row1 = sheet.createRow(i);
            row1.createCell(0).setCellValue(i);
            row1.createCell(1).setCellValue(template.getName());
            row1.createCell(2).setCellValue(template.getClassHour());
            row1.createCell(3).setCellValue(template.getType()==10?"理论":"实践");
            i++;
        }
        FileOutputStream output = new FileOutputStream( "D://aa.xls");
        wb.write(output);
        output.flush();
    }
    @RequestMapping(value = "/importResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(httpMethod = "GET", value = "导入课程模板结果", response = Void.class, notes = "导入课程模板结果<br><br><b>@author hsh</b>")
    public ResponseEntity<?> importResult(@RequestHeader("Authorization") String token,
                                          @ApiParam(value = "templateId", required = true) @RequestParam(value = "templateId") Long templateId) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }
        ImportResultDomain result = importService.importResult(account.getId(), templateId);
        return new ResponseEntity(result, HttpStatus.OK);
    }

}
